package com.applink.sell_proof;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import jp.gnt.mobion_foodnavi.utils.CameraUtils;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.MethodParams;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.constant.ItemStatus;
import com.applink.sell_proof.database.table.ClaimDBHelper;
import com.applink.sell_proof.dialog.EAlertDialog;
import com.applink.sell_proof.fragment.InvoiceBrieftFragment;
import com.applink.sell_proof.fragment.InvoiceDetail;
import com.applink.sell_proof.model.Claim;
import com.applink.sell_proof.model.ClaimImage;
import com.applink.sell_proof.model.MyImage;
import com.applink.sell_proof.model.Product;
import com.applink.sell_proof.select.photos.MultiPhotoSelectActivity;
import com.applink.sell_proof.urlimageviewhelper.BaseClaimPagerAdapter.OnItemClaimChangeListener;
import com.applink.sell_proof.urlimageviewhelper.GalleryClaimViewPager;
import com.applink.sell_proof.urlimageviewhelper.UrlPagerClaimAdapter;

public class BaseClaim extends BaseActionBarActivity implements Observer {

	public static final int REQUEST_TAKE_PHOTO = 0x01;
	public static final int ACTIVITY_SELECT_IMAGE = 2;

	public static List<ClaimImage> StorageImages = new ArrayList<ClaimImage>();

	protected Context mContext;

	protected List<Product> mProducts = new ArrayList<Product>();
	protected List<ClaimImage> mClaimImages = new ArrayList<ClaimImage>();
	protected List<ClaimImage> mRemoveClaimImages = new ArrayList<ClaimImage>();

	protected ViewGroup mBrieftLayout;

	protected ImageView imgNext;
	protected ImageView imgBack;
	protected ImageView imgDeleteImage;
	protected ImageView imgDeleteAllImages;
	protected ImageView imgNoPhoto;
	protected ImageView imgZoomIn;
	protected ImageView imgZoomOut;

	protected Button imgTakePhoto;
	protected Button imgSelectGallery;
	protected Button imgRotateRight;
	protected Button imgRotateLeft;

	protected GalleryClaimViewPager mViewPager;

	protected UrlPagerClaimAdapter pagerAdapter;

	protected boolean mReloadMenu = false;

	private int positionImage = 0;

	public static BaseClaim instantBaseClaim;

	@Override
	protected void onCreate(Bundle saveInstanceState) {

		super.onCreate(saveInstanceState);
		setContentView(R.layout.detail_claim);
		instantBaseClaim = this;
		mContext = this;
		initView();
		System.out.println("<<<Data local =  " + ClaimDBHelper.getClaimByStatus("'" + ItemStatus.DRAFT + "','" + ItemStatus.SUBMITTED + "','"
				+ ItemStatus.VERIFIED_SUCCESSFUL + "','"
				+ ItemStatus.VERIFIED_UNSUCCESSFUL + "'").size());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {

		case REQUEST_TAKE_PHOTO:
			if (resultCode == Activity.RESULT_OK) {

				imgNoPhoto.setVisibility(View.GONE);
				mViewPager.setVisibility(View.VISIBLE);

				showImage(mClaimImages);
			}
			break;

		case ACTIVITY_SELECT_IMAGE:
			if (resultCode == Activity.RESULT_OK) {
				if (StorageImages.size() > 0) {

					for (ClaimImage ic : StorageImages) {

						if (mClaimImages.contains(ic))
							continue;

						mClaimImages.add(ic);
					}
				}

				showImage(mClaimImages);
			}
			break;

		case SearchProductModel.SEARCH_PRODUCT:
			if (resultCode == Activity.RESULT_OK) {
				String modelname = data.getStringExtra("model_name");
				String modelno = data.getStringExtra("model_no");
				long product_id = data.getLongExtra("product_id", 0);
				Product productModel = new Product();
				productModel.setModelName(modelname);
				productModel.setModelNo(modelno);
				productModel.setProductId(product_id);

				InvoiceDetail invoiceDetail = (InvoiceDetail) getSupportFragmentManager()
						.findFragmentByTag(InvoiceDetail.TAG);

				invoiceDetail.setProductModel(productModel);

				break;
			}
		case SearchOpportunity.SEARCH_OPPORTUNITY:
			if (resultCode == Activity.RESULT_OK) {

				InvoiceBrieftFragment invoiceHeader = (InvoiceBrieftFragment) getSupportFragmentManager()
						.findFragmentByTag("InvoiceBrieftFragment");
				String opportunity_id = data.getStringExtra("opportunity_id");
				String name = data.getStringExtra("opportunity_name");
				invoiceHeader.setOpportunityId(opportunity_id, name);
			}
			break;
		}
	}

	/**
	 * setting all the listeners
	 */
	protected void listener() {
		imgDeleteAllImages.setOnClickListener(this);
		imgDeleteImage.setOnClickListener(this);
		imgNext.setOnClickListener(this);
		imgBack.setOnClickListener(this);
		imgZoomIn.setOnClickListener(this);
		imgZoomOut.setOnClickListener(this);

		imgTakePhoto.setOnClickListener(this);
		imgSelectGallery.setOnClickListener(this);
		imgRotateLeft.setOnClickListener(this);
		imgRotateRight.setOnClickListener(this);
	}

	/**
	 * initialize all the reference to view objects
	 */
	protected void initView() {
		
		if (imgRotateLeft == null) {
			imgRotateLeft = (Button) findViewById(R.id.rotate_left_detail_claim);
		}

		if (imgRotateRight == null) {
			imgRotateRight = (Button) findViewById(R.id.rotate_right_detail_claim);
		}

		if (imgTakePhoto == null) {
			imgTakePhoto = (Button) findViewById(R.id.take_photo);
		}

		if (imgSelectGallery == null) {
			imgSelectGallery = (Button) findViewById(R.id.select_gallery_detail_claim);
		}

		if (imgDeleteImage == null) {
			imgDeleteImage = (ImageView) findViewById(R.id.img_delete_image_detail_claim);
		}

		if (imgDeleteAllImages == null) {
			imgDeleteAllImages = (ImageView) findViewById(R.id.img_delete_all_image_detail_claim);
		}

		if (imgNext == null) {
			imgNext = (ImageView) findViewById(R.id.img_next_image_detail_claim);
		}

		if (imgBack == null) {
			imgBack = (ImageView) findViewById(R.id.img_back_image_detail_claim);
		}

		if (mViewPager == null) {
			mViewPager = (GalleryClaimViewPager) findViewById(R.id.gallery_detail_claim);
		}

		if (imgNoPhoto == null) {
			imgNoPhoto = (ImageView) findViewById(R.id.img_no_photo_detail_claim);
		}

		if (imgZoomIn == null) {
			imgZoomIn = (ImageView) findViewById(R.id.img_zoom_in_image_detail_claim);
		}

		if (imgZoomOut == null) {
			imgZoomOut = (ImageView) findViewById(R.id.img_zoom_out_image_detail_claim);
		}

		if (mBrieftLayout == null) {
			mBrieftLayout = (ViewGroup) LayoutInflater.from(this).inflate(
					R.layout.invoice_brieft, null);
		}

		listener();
	}
	
	public void showData(){
		
	}

	protected void createClaim(Claim claim) {
		claim.setImages(mClaimImages);
		DataHelper.getInstance().createClaim(claim);
		showloading();
	}

	protected void saveClaim(Claim claim) {
		claim.setImages(mClaimImages);
		DataHelper.getInstance().saveClaim(claim);
		showloading();
	}

	protected boolean ClaimDetailSelected() {
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();

		transaction.add(R.id.invoice_container, new InvoiceDetail(),
				InvoiceDetail.TAG);

		transaction.setCustomAnimations(R.anim.slide_left_right,
				R.anim.slide_right_left);

		transaction.commit();

		return true;
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);

		switch (v.getId()) {
		case R.id.img_zoom_in_image_detail_claim:
			// mViewPager.Zoom(true);
			break;

		case R.id.img_zoom_out_image_detail_claim:
			// mViewPager.Zoom(false);
			break;
		case R.id.img_next_image_detail_claim:
			if (positionImage + 1 < mClaimImages.size()) {
				positionImage = positionImage + 1;
				mViewPager.setCurrentItem(positionImage);
			}
			break;

		case R.id.img_back_image_detail_claim:
			if (positionImage > 0) {
				positionImage = positionImage - 1;
				mViewPager.setCurrentItem(positionImage);
			}

			break;
		case R.id.img_delete_all_image_detail_claim: {

			DialogFragment dialogFragment = new EAlertDialog(
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							switch (which) {
							case Dialog.BUTTON_POSITIVE:

								for (ClaimImage ci : mClaimImages) {

									if (ci.getClaimImageId() == 0)
										continue;

									ci.setDelete(true);
									mRemoveClaimImages.add(ci);
								}

								mClaimImages.clear();

								imgNoPhoto.setVisibility(View.VISIBLE);
								mViewPager.setVisibility(View.GONE);
								dialog.dismiss();
								break;
							case Dialog.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							default:
								break;
							}

						}
					}, "Warning!!!", mContext.getString(android.R.string.no),
					mContext.getString(android.R.string.yes),
					"Do you want to delete all the images?");

			dialogFragment.show(this.getSupportFragmentManager(), null);
			break;
		}

		case R.id.img_delete_image_detail_claim: {

			ClaimImage ci = mClaimImages.get(positionImage);

			if (ci.getClaimImageId() != 0) {
				ci.setDelete(true);
				mRemoveClaimImages.add(ci);
			}

			mClaimImages.remove(positionImage);
			showImage(mClaimImages);

			break;
		}
		case R.id.take_photo: {

			Intent intCreateClaim = CameraUtils
					.startCameraToTakePhoto(getApplicationContext());

			if (intCreateClaim != null) {

				ClaimImage ci = new ClaimImage();

				ci.setImageLocation((Uri) intCreateClaim
						.getParcelableExtra(MediaStore.EXTRA_OUTPUT));

				mClaimImages.add(ci);

				try {
					startActivityForResult(intCreateClaim, REQUEST_TAKE_PHOTO);
				} catch (ActivityNotFoundException ane) {
					Log.e("hc",
							"ERROR when calling camera app: " + ane.toString());
				}
			}
			break;
		}
		case R.id.select_gallery_detail_claim: {
			Intent intCreateClaim = new Intent(mContext,
					MultiPhotoSelectActivity.class);
			startActivityForResult(intCreateClaim, ACTIVITY_SELECT_IMAGE);
			break;
		}
		case R.id.rotate_left_detail_claim:
			if (mClaimImages.size() > 0) {
				// mViewPager.Rotate(false);

				mClaimImages.get(positionImage).doRotate(false);
			}
			break;
		case R.id.rotate_right_detail_claim:
			if (mClaimImages.size() > 0) {
				// mViewPager.Rotate(true);

				mClaimImages.get(positionImage).doRotate(true);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		hideloading();

		final DataResult result = (DataResult) data;
		Methods method = result.getMethodName();

		String title = "";

		switch (method) {
		case updateClaim:
			title = "Update Claim";
			break;
		case createClaim:
			title = "Create Claim";
			break;
		case saveClaim:
			title = "Save Claim As Draft";
			break;
		case deleteClaim:
			title = "Delete Claim";
			break;
		default:
			return;
		}

		String closeBtnText = "close";
		String resultText = "";//"Unsuccessful";

		android.content.DialogInterface.OnClickListener listener = null;

		if (result.getData() != null) {
			// has a valid response
			resultText = "Successful";

			listener = new android.content.DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

					switch (which) {
					case Dialog.BUTTON_NEGATIVE:

						Intent intent = new Intent(mContext,
								ClaimActivity.class);

						MethodParams mp = result.getMethodParam();
						String[] localids = (String[]) mp
								.getTag(Constant.ID_LOCAL);

						intent.putExtra(Constant.ID_LOCAL, localids);

						mContext.startActivity(intent);
						dialog.dismiss();
						break;
					default:
						break;
					}

				}
			};
		} else {

			MethodParams mp = result.getMethodParam();

			resultText += " " + mp.getInputData();
		}

		DialogFragment dialogFragment = new EAlertDialog(listener, title,
				closeBtnText, null, resultText);
		dialogFragment.show(this.getSupportFragmentManager(), null);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.claim_detail: {
			return ClaimDetailSelected();
		}
		case R.id.menu_save_claim: {
			saveClaim();
			break;
		}
		case R.id.menu_submit_claim: {

			InvoiceBrieftFragment invoiceHeader = (InvoiceBrieftFragment) getSupportFragmentManager()
					.findFragmentByTag("InvoiceBrieftFragment");

			Claim claim = invoiceHeader.getClaimHeader();

			setClaimProducts(claim);			

			createClaim(claim);
			break;
		}
		default:
			break;
		}

		return false;
	}

	public void saveClaim() {
		InvoiceBrieftFragment invoiceHeader = (InvoiceBrieftFragment) getSupportFragmentManager()
				.findFragmentByTag("InvoiceBrieftFragment");

		Claim claim = invoiceHeader.getClaimHeader();		
		setClaimProducts(claim);
//		
//		for(int i = 0;i< claim.getProducts().size();i++){
//			int countServiceTag = getCount(claim.getProducts().get(i).getService_tag());
//			if(!((countServiceTag + 1) == claim.getProducts().get(i).getQuantity())){
//				Toast.makeText(mContext, "Please check on the Service Tag", Toast.LENGTH_SHORT).show();
//				return;
//			}
//		}		
		saveClaim(claim);
	}	
	

	/**
	 * setter for mProducts
	 * 
	 * @param products
	 */
	public void setListProducts(List<Product> products) {
		mProducts = products;
	}

	/**
	 * getter of mProducts
	 * 
	 * @return
	 */
	public List<Product> getProducts() {
		return mProducts;
	}

	/**
	 * show the images by string paths
	 * 
	 * @param items
	 */
	private void showImage(List<ClaimImage> items) {

		if (items.size() == 0) {
			mViewPager.setVisibility(View.GONE);
			imgNoPhoto.setVisibility(View.VISIBLE);
			return;
		}

		mViewPager.setVisibility(View.VISIBLE);
		imgNoPhoto.setVisibility(View.GONE);

		pagerAdapter = new UrlPagerClaimAdapter(this, new ArrayList<MyImage>(
				items));
		mViewPager.setOffscreenPageLimit(3);
		mViewPager.setAdapter(pagerAdapter);
		pagerAdapter.setOnItemChangeListener(new OnItemClaimChangeListener() {

			@Override
			public void onItemChange(int currentPosition) {
				positionImage = currentPosition;

			}
		});
	}

	private void setClaimProducts(Claim c) {
		if (mProducts.size() == 0) {
			try {

				InvoiceDetail invoiceDetail = (InvoiceDetail) getSupportFragmentManager()
						.findFragmentByTag(InvoiceDetail.TAG);
				mProducts = invoiceDetail.getProducts();
			} catch (Exception e) {
			}
		}

		c.setProducts(mProducts);
	}

//	@Override
//	public boolean onPrepareOptionsMenu(Menu menu) {
//		MenuItem item = menu.findItem(R.id.claim_detail);
//		if (Constant.CHECK_OPPORTUNITY) {
//			item.setVisible(false);
//		}
//		// else{
//		// // item.setVisible(true);
//		// }
//
//		return super.onPrepareOptionsMenu(menu);
//	}
}
